package cn.darkhorse.alarm.service.alarm;

import cn.darkhorse.alarm.pojo.AlarmParameterSettings;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;

/**
 * 变量，限值预警
 * @author yuanjun
 * @since 2023/4/7 13:46
 */
@Component
public class LimitValueAlarm extends BaseAlarm implements Alarm{
    @Resource
    private StringRedisTemplate stringRedisTemplate;

   @Override
    public void doAlarm(AlarmParameterSettings settings, Map<String,Object> data) {
       String value = (String) data.get(settings.getFieldName());
       if(StringUtils.isBlank(value)) {
            return;
        }

        if (settings.getAlarmType().equals(ALARM_LIMIT_VALUE)) {
            // 获取最大最小值
            String alarmMessage = settings.getAlarmMessage();
            JSONArray jsonArray = JSONArray.parse(alarmMessage);

            BigDecimal maxValue = null;
            BigDecimal minValue = null;
            for (Object obj : jsonArray) {
                JSONObject jsonObject = (JSONObject) obj;
                String v1 = (String) jsonObject.get("maxValue");
                if (StringUtils.isNotBlank(v1)) {
                    maxValue = BigDecimal.valueOf(Double.parseDouble(v1));
                }

                String v2 = (String) jsonObject.get("minValue");
                if (StringUtils.isNotBlank(v2)) {
                    minValue = BigDecimal.valueOf(Double.parseDouble(v2));
                }
            }

            // 找不到上下限值，返回不做处理
            if (maxValue == null || minValue == null) {
                return;
            }

            BigDecimal valueB = BigDecimal.valueOf(Double.parseDouble(value));

            if (valueB.compareTo(maxValue) == 1) {
                // 大于最大值，报警
                writeAlarmMsg(settings, data);
            }

            if (valueB.compareTo(minValue) == -1) {
                // 小于最小值，报警
                writeAlarmMsg(settings, data);
            }
        }
    }

    private void writeAlarmMsg(AlarmParameterSettings settings, Map<String,Object> data) {
        sendAlarmFlag(settings,data);
    }

    public static void main(String[] args) {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("maxValue","500");
        jsonObject.put("msg","超过最大值");
        jsonArray.add(jsonObject);
        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("minValue","100");
        jsonObject2.put("msg","超过最小值");
        jsonArray.add(jsonObject2);

        System.out.println(jsonArray);




    }
}
